package com.tanhua.server.service;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.cloud.commons.lang.StringUtils;
import com.tanhua.autoconfig.template.OssTemplate;
import com.tanhua.commons.Constants;
import com.tanhua.commons.exception.TanHuaException;
import com.tanhua.dubbo.api.db.UserInfoApi;
import com.tanhua.dubbo.api.mongo.CommentApi;
import com.tanhua.dubbo.api.mongo.MovementApi;
import com.tanhua.dubbo.api.mongo.VisitorsApi;
import com.tanhua.model.db.UserInfo;
import com.tanhua.model.mongo.Friend;
import com.tanhua.model.mongo.Movement;
import com.tanhua.model.mongo.Visitors;
import com.tanhua.model.vo.MovementVo;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.TodayBest;
import com.tanhua.server.interceptor.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class MovementService {

    @DubboReference
    private MovementApi movementApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @DubboReference
    private CommentApi commentApi;

    @DubboReference
    private VisitorsApi visitorsApi;

    @Autowired
    private OssTemplate ossTemplate;

    @Autowired
    private MqMessageService mqMessageService;

    /**
     * 发布动态
     */
    public void postMovement(MultipartFile[] imageContent, Map<String, String> params) {
        String textContent = params.get("textContent");
        if (StringUtils.isEmpty(textContent)) {
            throw new TanHuaException("动态内容不能为空！");
        }
        List FilePathlist = new ArrayList();
        try {
            for (MultipartFile multipartFile : imageContent) {
                String FilePath = ossTemplate.upload(multipartFile.getOriginalFilename(), multipartFile.getInputStream());
                FilePathlist.add(FilePath);
            }
        } catch (IOException e) {
            throw new TanHuaException("图片上传失败");
        }

        Movement movement = new Movement();
        movement.setUserId(UserHolder.getUserId());
        movement.setTextContent(textContent);
        movement.setMedias(FilePathlist);
        movement.setLocationName(params.get("location"));
        movement.setLongitude(params.get("longitude"));
        movement.setLatitude(params.get("latitude"));
        Movement post = movementApi.post(movement);

        mqMessageService.sendLogMsg("0201","movement",UserHolder.getUserId().toString());

    }

    /**
     * 获取好友动态
     *
     * @param pageResult
     * @return
     */
    public PageResult friendMovement(PageResult pageResult) {
        List<Friend> friendList = movementApi.getFriend(UserHolder.getUserId());
        PageResult<Movement> movement = movementApi.getMovement(friendList, pageResult);
        List<MovementVo> voList = new ArrayList<>();
        for (Movement vo : movement.getItems()) {
            UserInfo userInfo = userInfoApi.getuserinfo(vo.getUserId(), null);
            MovementVo init = MovementVo.init(userInfo, vo);
            String key = Constants.MOVEMENTS_INTERACT_KEY + vo.getId();
            String lovekey = Constants.MOVEMENT_LOVE_HASHKEY + UserHolder.getUserId();
            String likekey = Constants.MOVEMENT_LIKE_HASHKEY + UserHolder.getUserId();
            String love = (String) stringRedisTemplate.opsForHash().get(key, lovekey);
            String like = (String) stringRedisTemplate.opsForHash().get(key, likekey);
            if (like != null) {
                init.setHasLiked(1);
            }
            if (love != null) {
                init.setHasLoved(1);
            }
            voList.add(init);
        }
        return new PageResult(movement.getPage(), movement.getPagesize(), movement.getCounts(), voList);
    }

    /**
     * 获取推荐动态
     *
     * @param pageResult
     * @return
     */
    public PageResult getRecommend(PageResult pageResult) {
        Long userId = UserHolder.getUserId();
        String keys = Constants.MOVEMENTS_RECOMMEND + UserHolder.getUserId();
        String recommend = stringRedisTemplate.opsForValue().get(keys);
        Long start = (pageResult.getPage() - 1) * pageResult.getPagesize();
        if (StringUtils.isNotEmpty(recommend)) {
            List<String> collect = Arrays.stream(recommend.split(",")).skip(start)
                    .limit(pageResult.getPagesize()).collect(Collectors.toList());
            PageResult<Movement> result = movementApi.getRecommend(pageResult, collect);
            List<Movement> movements = result.getItems();
            List<MovementVo> voList = new ArrayList<>();
            for (Movement movement : movements) {
                UserInfo userInfo = userInfoApi.getuserinfo(movement.getUserId(), null);
                MovementVo init = MovementVo.init(userInfo, movement);
                ObjectId id = movement.getId();
                boolean like = commentApi.isLike(id, userId);
                boolean love = commentApi.isLove(id, userId);
                if (like) {
                    init.setHasLiked(1);
                }
                if (love) {
                    init.setHasLoved(1);
                }
                voList.add(init);
            }
            return new PageResult(result.getPage(), result.getPagesize(), (long) collect.size(), voList);

        }

        PageResult<Movement> result = movementApi.getRecommend(pageResult, null);
        List<Movement> items = result.getItems();
        List<MovementVo> voList = new ArrayList<>();
        for (Movement movementVo : items) {
            UserInfo userInfo = userInfoApi.getuserinfo(movementVo.getUserId(), null);
            MovementVo init = MovementVo.init(userInfo, movementVo);
            ObjectId id = movementVo.getId();
            boolean like = commentApi.isLike(id, userId);
            boolean love = commentApi.isLove(id, userId);
            if (like) {
                init.setHasLiked(1);
            }
            if (love) {
                init.setHasLoved(1);
            }
            voList.add(init);
        }

        return new PageResult(result.getPage(), result.getPagesize(), result.getCounts(), voList);
    }

    /**
     * 喜欢动态
     *
     * @param id
     */
    public Integer loveMovement(ObjectId id) {
        String key = Constants.MOVEMENTS_INTERACT_KEY + id;
        String hackey = Constants.MOVEMENT_LOVE_HASHKEY + UserHolder.getUserId();
        Integer integer = movementApi.loveMovement(id, UserHolder.getUserId());
        stringRedisTemplate.opsForHash().put(key, hackey, "1");
        mqMessageService.sendLogMsg("0204","lovemovement",integer.toString());
        return integer;
    }

    /**
     * 取消喜欢
     */
    public Integer unloveMovement(ObjectId id) {

        String key = Constants.MOVEMENTS_INTERACT_KEY + id;
        String hackey = Constants.MOVEMENT_LOVE_HASHKEY + UserHolder.getUserId();
        String value = (String) stringRedisTemplate.opsForHash().get(key, hackey);
        Integer integer = movementApi.unloveMovement(id, UserHolder.getUserId());
        stringRedisTemplate.opsForHash().delete(key, hackey);
        mqMessageService.sendLogMsg("0204","unlovemovement",integer.toString());
        return integer;

    }

    /**
     * 点赞动态
     *
     * @param id
     * @return
     */
    public Integer likeMovement(ObjectId id) {
        Integer integer = movementApi.likeMovement(id, UserHolder.getUserId());
        String key = Constants.MOVEMENTS_INTERACT_KEY + id;
        String hachkey = Constants.MOVEMENT_LIKE_HASHKEY + UserHolder.getUserId();
        stringRedisTemplate.opsForHash().put(key, hachkey, "1");
        mqMessageService.sendLogMsg("0203","likemovement",integer.toString());
        return integer;
    }

    /**
     * 取消点赞
     */
    public Integer dislikeMovement(ObjectId id) {
        Integer dislike = movementApi.dislike(id, UserHolder.getUserId());
        String key = Constants.MOVEMENTS_INTERACT_KEY + id;
        String hachkey = Constants.MOVEMENT_LIKE_HASHKEY + UserHolder.getUserId();
        stringRedisTemplate.opsForHash().delete(key, hachkey);
        mqMessageService.sendLogMsg("0206","dislikemovement",dislike.toString());
        return dislike;
    }

    /**
     * 获取用户动态
     *
     * @param pageResult
     * @param id
     * @return
     */
    public PageResult<MovementVo> allMovement(PageResult pageResult, Long id) {
        if (id == null) {
            id = UserHolder.getUserId();
        }
        PageResult<Movement> allMovement = movementApi.getAllMovement(pageResult, id);
        List<Movement> movementItems = allMovement.getItems();
        List<MovementVo> voList = new ArrayList<>();
        for (Movement movementVo : movementItems) {
            UserInfo userInfo = userInfoApi.getuserinfo(movementVo.getUserId(), null);
            MovementVo init = MovementVo.init(userInfo, movementVo);
            String key = Constants.MOVEMENTS_INTERACT_KEY + movementVo.getId();
            String lovekey = Constants.MOVEMENT_LOVE_HASHKEY + UserHolder.getUserId();
            String likekey = Constants.MOVEMENT_LIKE_HASHKEY + UserHolder.getUserId();
            String love = (String) stringRedisTemplate.opsForHash().get(key, lovekey);
            String like = (String) stringRedisTemplate.opsForHash().get(key, likekey);
            if (like != null) {
                init.setHasLiked(1);
            }
            if (love != null) {
                init.setHasLoved(1);
            }
            voList.add(init);
        }

        return new PageResult<>(allMovement.getPage(), allMovement.getPagesize(), allMovement.getCounts(), voList);
    }

    /**
     * 获取单个动态
     *
     * @param id
     * @return
     */
    public MovementVo getMovement(ObjectId id) {
        Movement movement = movementApi.getOneMovement(id);
        UserInfo getuserinfo = userInfoApi.getuserinfo(movement.getUserId(), null);
        MovementVo init = MovementVo.init(getuserinfo, movement);
        String key = Constants.MOVEMENTS_INTERACT_KEY + init.getId();
        String lovekey = Constants.MOVEMENT_LOVE_HASHKEY + UserHolder.getUserId();
        String likekey = Constants.MOVEMENT_LIKE_HASHKEY + UserHolder.getUserId();
        String love = (String) stringRedisTemplate.opsForHash().get(key, lovekey);
        String like = (String) stringRedisTemplate.opsForHash().get(key, likekey);
        if (like != null) {
            init.setHasLiked(1);
        }
        if (love != null) {
            init.setHasLoved(1);
        }
        return init;
    }

    /**
     * 首页获取访客列表
     *
     * @return
     */
    public List<TodayBest> findLast4() {
        //查询用户查看最新访客时间
        String redisKey = Constants.VISITORS_USER;
        String whoKey = UserHolder.getUserId().toString();
        String time = (String) stringRedisTemplate.opsForHash().get(redisKey, whoKey);
        if (StringUtils.isNotEmpty(time)) {
            Visitors visitors = visitorsApi.findLastVisitor(UserHolder.getUserId());
            if (BeanUtil.isNotEmpty(visitors)){
                Long date = visitors.getDate();
                //判断 最近访问访客列表的时间是否大于最新访客访问时间，如果是就不显示，如果不是就返回最新访客记录
                if (date.longValue() < Long.valueOf(time).longValue()) {
                    return new ArrayList<>();
                }
            }
        }
        List<Visitors> visitors = visitorsApi.findLast4(UserHolder.getUserId());
        List<Long> userIds = visitors.stream().map(Visitors::getVisitorUserId).collect(Collectors.toList());
        List<UserInfo> usersByid = userInfoApi.getUsersByid(userIds);
        List<TodayBest> voList = new ArrayList<>();
        if (usersByid != null) {
            voList = usersByid.stream().map(u -> TodayBest.init(u, null)).collect(Collectors.toList());
        }
        return voList;
    }
}
